<?php
include_once ROOT.'/model/dao/UserDao.php';
$userDao = new UserDao();
if(!empty($_SESSION['user'])){
	die(json_encode($_SESSION['user']));
}

if(empty($_POST['email']) && empty($_POST['password'])){
	header("HTTP/1.0 400 Bad Request");
	die();
}
$error = "";
if(empty($_POST['email']) || empty($_POST['password'])){
	$error .= "Email and password must not be empty<br/>";
}
$email = addslashes($_POST['email']);
$user = $userDao->getByEmail($email);
if(empty($user)){
	$error .= "This email doesn't exist<br/>";
}
if(!empty($user) && $user->getPassword()!=encode($_POST['password'])){
	$error .= "Wrong password<br/>";
}
if(!empty($error)){
	header("HTTP/1.0 400 Bad Request");
	die(json_encode(array('error'=>$error)));
}
$_SESSION['user']['id'] = $user->getId();
$_SESSION['user']['firstname'] = $user->getFirstname();
$_SESSION['user']['lastname'] = $user->getLastname();
$_SESSION['user']['email'] = $user->getEmail();
echo json_encode($_SESSION['user']);